#MYOWD=/data/data/com.termux/files/home/gitee/emp #for termux
#MYOWD=/data/data/com.termux/files/home/emp
#MYOWD=/home/h/data/gitee/emp/  # my linux
#MYOWD=$(pwd) #your current directory
MYOWD=$(pwd)
#sed "/^MYOWD=/cMYOWD=$MYOWD"  $MYOWD/damon.sh -i
sed "/^MYOWD=/cMYOWD=$MYOWD" $MYOWD/*.sh -i
source "$MYOWD/base.sh"
source "$MYOWD/net.sh" 'source'
RUN="/bin/bash $MYOWD/damon.sh run"
ifs=$IFS
dir=$(lget dir)
getPid() {
	Pid=$(ps aux | grep "$RUN" | awk '!/grep/{print $2}')
	echo $Pid
	Set Pid $Pid
}
getpid() {
	#pid=$(ps aux|grep "$Player_Cmd.*$(lget url)"|awk 'NR==1{print $2}')
	pid=$(ps aux | grep "$Player_Cmd" | awk '!/grep/{print $2}')
	echo $pid
	lset pid $pid
}
toggle() {
	state=$(lget state)
	if [[ $state = 'play' ]]; then
		kill -s SIGSTOP $(getpid)
		lset state pause
	else
		kill -s SIGCONT $(getpid)
		lset state play
	fi
	echo 切换播放状态: state $(lget state)
}
next() {
	kill $(getpid)
}
pre() {
	num=$(($(lget num) - 2))
	lset num $num
	kill $(getpid)
}
list() {
	lset mode list
}
loop() {
	lset mode loop
}
shuffle() {
	lset mode shuffle
}
close() {
	kill $(getPid)
	kill $(getpid)
}
run() {
	if [[ -f $Tmp_File ]]; then
		$RUN &
	else
		switch list $(Get Playlist)
	fi
}
Re() {
	close
	run
}
scan() {
	IFS=','
	#dir='/home/h/data/music'
	for t in $(Get Types); do
		find $1 -name "*\.$t" |
			sed "s#.*#id:0,filename:&,type:$t#"
	done | grep -n ".*" | sed -E 's#([^:]*):#num:\1,#1'
	IFS=$ifs
}
dirinit() {
	l=$List_Dir
	if [[ -d $2 || $1 = 'all_lists' ]]; then
		if [[ $1 != 'all_lists' ]]; then
			scan $2 >$l/$1 # scan dir file
		fi
		cat $l/$1
		if [[ $(sed -n $= $l/$1) -eq 0 ]]; then
			echo "目录没有音乐📄 exit..."
			exit
		fi
		Get info filename $l/$1 | grep -o "/.*/" | sort | uniq >$l/.$1
		cat $l/.$1
		echo "总计 $(sed -n $= $l/$1), 祝你生活愉快. 🫡🫡"

		echo '' >>$Config_File
		echo '' >>$Config_File
		awk -vRS='' 'NR==2' $Config_Dir/.config.md >>$Config_File

		Playlist=default
		lset name $1
		Playlist=$1
		lset dir $2
		lcat
	else
		echo "目录不存在,输入正确？ 🍐"
		exit
	fi
}
type_filte() {
	IFS=','
	lget 'type'
	for t in $(lget 'type'); do
		grep ".*type:$t" "$1"
	done
	IFS=$ifs
}
dir_filte() {
	l=$List_Dir
	f="$Playlist"
	if [[ -f "$l/$f" && -f "$l/.$f" ]]; then
		dir=$(grep -o "^.*$(lget dir)[^/]*" "$l/.$f" | sort | uniq)
		for d in $dir; do
			grep "filename:$d" "$l/$f"
		done
	fi
	grep "type:net" "$l/$f"
	grep "type:mv" "$l/$f"
}
lists() {
	case $1 in
	get)
		sed -nE '/^- name:/s/^- name: ([^ ]*).*/\1/p' $Config_File
		;;
	dir)
		ds=$(cat $List_Dir/.$Playlist)
		ds=$(echo $ds | sed 's#/#\n#g' | sort | uniq)
		echo $ds
		;;
	esac
	if [[ $# -eq 0 ]]; then
		sed -n '/^- name:/s/^- name: //p' $Config_File
	fi
}
Filte() {
	play=$(lget play)
	echo $play
	if [[ $play = 'all' ]]; then
		play='flac net mv mp3'
	fi

	for p in $play; do
		echo "添加 $p 格式 $A"
		case $p in
		mp3 | flac)
			gr="type:$p"
			;;
		mv)
			gr="mv:[^0][0-9]*"
			;;
		net)
			gr="-v id:0"
			;;
		*)
			echo "这种格式还没做适配哟 🍎"
			exit
			;;
		esac
		grep $gr $Tmp_File >>$Tmp_File.use
		#grep -v 'mv:0' $Tmp_File
	done
	lset totalnum $(sed -n $= $Tmp_File.use)
}
switch() {
	case $1 in
	dir | type)
		echo '你可以试试这些: 🍎'
		[[ $1 = dir ]] && lists dir
		[[ $1 = type ]] && echo 'all net mv flac mp3'

		if [[ ! -z $2 ]]; then
			close
			lset $1 "$2"
		else
			exit
		fi
		;;
	list)
		close
		for l in $(lists get); do
			if [[ $l = *$2* ]]; then
				let n++
			fi
			if [[ $l = $2 ]]; then
				n=1
				break
			fi
		done

		if [[ $n -eq 1 ]]; then
			Playlist="$l"
			list_ok=yes
		else
			echo 'list not unique'
			list_ok=no
		fi

		if [[ $list_ok != 'yes' || -z $2 ]]; then
			echo "$A 你的列表: cc lists"
			lists | grep -n '.*'
			read -p 'input: ' n
			if [[ -z $(lists | sed -n ${n}p) ]]; then
				echo 'EEEE , input error'
				exit
			fi
			Playlist=$(lists | awk "NR==$n{print \$1}")
		fi
		;;
	'type')
		echo '试试这些' 'all flac net mv mp3'
		close
		lset type $2
		;;
	*)
		echo '''请输入正确的参数：
			cc switch list youlist
			cc switch dir youdir_or_subdir
			cc switch type mp3  #mp3,flac,net,mv
			'''
		exit
		;;
	esac
	rm -f $Tmp_File
	rm -f $Tmp_File.use
	dir_filte >$Tmp_File.1
	type_filte $Tmp_File.1 >$Tmp_File
	sed '/flac,mp3,net,mv/d' -i $Tmp_File
	#	type_filte  $Tmp_File.1
	Set Playlist "$Playlist"
	lset totalnum $(sed -n $= $Tmp_File)
	echo "切换$1 为 $(Get Playlist), 歌曲数量变更为: $(lget totalnum) 🍎"
	Filte
	run
}
create() {
	case $1 in
	list)
		dirinit $2 $3
		switch list $2
		;;
	net)
		create_net $2 choose_pid
		switch list $2
		;;
	all)
		sed '/- name: all_lists/,/^$/d' -i $Config_File
		name="$List_Dir/all_lists"
		rm $name
		(ls $List_Dir | xargs -i cat $List_Dir/{}) >$Tmp_File.t
		cat $Tmp_File.t >$name

		name="$List_Dir/.all_lists"
		rm $name
		(ls $List_Dir | xargs -i cat $List_Dir/.{}) >$Tmp_File.t
		cat $Tmp_File.t >$name

		dirinit all_lists
		switch list all_lists
		;;
	esac
}
reset() {
	close
	awk -vRS='' 'NR==1' $Config_Dir/.config.md >$Config_File
	create list i /home/h/data/music
}
delete() {
	sed -n "/^- name: $1/,/^$/ p" $Config_File
	if [[ -z $(sed -n "/^- name: $1/ p" $Config_File) ]]; then
		echo "没有这个目录啦，检查一下 $A"
		exit
	fi
	echo '''
	你确认要删除吗？
	'''
	read -p 'yes or no' y
	if [[ $y = 'yes' ]]; then
		sed "/^- name: $1/,/^$/ d" -i.k $Config_File
	fi
	echo '------'
}

#reset
#lset 'type' 'mp3,flac,mv,net'
#switch dir yzk
Help() {
	echo '''欢迎使用emp: 一个优雅的音乐播放器  🍎🍎🍎
	ccc is a sylic, the same as ./client.sh
帮助    创建列表,如:ccc  create list 原神 /home/h/music
帮助    generate all列表,如:ccc  create all #from list/*
帮助    delete列表,如:ccc delete yuanshen
帮助    delete列表,如:ccc delete #delete all playlist
帮助    delete file,如:rm .cache/playlist -rf

	切换模式：      运行状态：
	list 列表	lcat 查看当前
	loop 循环	toggle 切换播放器play/pause状态
	shuffle 随机

	lists 列出可用的列表
	switch list your-list 切换列表
	switch type mp3 切换类型，可选 mp3,flac,mv,net
	play mp3/mv/net/flac/all/glike/like/gdislike/dislike/default
	# 快速播放
	create list your-list your-list-dir 新建列表
	switch dir your-dir 切换列表使用的目录

	delete xxx  
	close 关 run 开; Re  重启; reset 重置

	pre 前一曲; next 下一曲

	like 添加到like列表，增加一次在当前列表出现的频数
	dislike ...dislike,  减少....

	#163 打开 网易云音乐交互 辅助功能，需要安装
QUICK START ---->
		local music? 
	ccc create list localmusic ~/ #scan ~/ music
	ccc play all  #other types /flac/net/mp3/mv
	ccc run
	ccc songs       #show a quick control bar
		no local music? 
first 	ccc P #交互式运行 netease music client
	sl #search playlist, choose your like
then    add
	ss  #search single songs, input number play
you can login
./net.sh login  #show help
./net.sh phone c # smk tips: you only need login in once
 and you can login in other channel at the same time,you
 and other"s playlist will saved by file, by default,my
 channel have login in ,you can run ` ccc P   ; l ` see
 my playlist 
'''
}
ss() {
	watch -n 1 " sed -n '/- name: $Playlist/,/^$/ p;' $Config_File"
}

play() {
	case $1 in
	mv | net | mp3 | flac | all)
		lset play $1
		;;
	like | dislike)
		cp "$List_Dir/.$Playlist.$1" $Tmp_File
		echo "切换: $Playlist $1 操作成功 🍎"
		;;
	default)
		cp "$List_Dir/.$Playlist" $Tmp_File
		echo "切换: $Playlist $1 操作成功 🍎"
		;;
	glike | gdislike)
		cp "$List_Dir/.global.${1//g/}" $Tmp_File
		echo cp "$List_Dir/.global.${1//g/}" $Tmp_File
		echo "切换: global ${1//g/} 操作成功 🍎"
		;;
	*)
		echo "请输入支持的类型哦 mv,mp3,net,flac $A"
		exit
		;;
	esac
	rm -f $Tmp_File.use
	Filte
	lset totalnum $(sed -n $= $Tmp_File.use)
	sed -n $= $Tmp_File.use
	next
}
like() {
	L=like
	[[ $1 = 'dislike' ]] && L=dislike
	f="$List_Dir/.$Playlist.$L"
	like="$List_Dir/.global.$L"
	l="$List_Dir/$Playlist"
	sed -n "$(lget num) p" $Tmp_File.use >>$f
	sed -n "$(lget num) p" $Tmp_File.use >>$like
	if [[ $1 = 'dislike' ]]; then
		sed "/$(lget filename)/ d" $Tmp_File.use -i $l
	else
		sed -n "$(lget num) p" $Tmp_File.use >>$l
	fi

	echo "$L: 操作成功 $(lget filename) 🍎"
}
dislike() {
	like dislike
	next
}
change_uid() {
	f=$Config_Dir/.163/jq.login
	fs=${f}all
	jq .uname $fs | grep -n ".*"
	read -p "输入:" n
	if [[ $n =~ [1-9] ]]; then
		let n--
		jq -s ".[$n]" $fs >$f
	else
		echo "你在瞎折腾吧。会被玩坏的啦 🍎"
		exit
	fi
	echo "更换uid: 操作完毕 🍎"
}
setnum() {
	#	lset num $1
	lset num $(($1 - 1))
	next
}
songs() {
	page=15
	n=$(lget num)
	t=$(lget totalnum)
	((t < 1)) || [[ ! -f $Tmp_File ]] && switch list
	while true; do
		[[ $n -lt 1 ]] && n=$t
		n=$(((n - 1) % t + 1))
		let n2=n+page
		#echo "$n,$n2"
		cat $Tmp_File.use | Get info filename | grep -n '.*' | sed -n "$n,$n2 p"
		echo ''
		echo "play? $n:$(sed -n ${n}p $Tmp_File.use | Get info filename) y/n"

		read -n1 -e -p 'input: ' c
		case $c in
		J) let n+=$page ;;
		j) let n+=1 ;;
		K) let n-=$page ;;
		k) let n-=1 ;;
		y) setnum $n ;;
		L) like ;;
		c)
			read tmp
			"$MYOWD/client.sh" $tmp
			exit
			;;
		n)
			read tmp
			if [[ $tmp =~ [0-9]+ ]]; then
				n=$tmp
				setnum $n
			fi
			;;
		q) exit ;;
		*)
			clear
			echo '''
				h: show this help
				q: exit
				c: run ccc cmd
				n: set play num
				k/K: pre/pre more  songs
				j/J: next/next more  songs
				y: enter
				L: like the same as `ccc like`
				'''
			read -n 1 -p 'press any key'
			;;
		esac
	done
}

case $1 in
func)
	$2
	;;
create*)
	$1 $2 $3 $4
	;;
switch)
	$1 $2 $3
	;;
search | lget | Get | lset | lists | delete | play)
	$1 $2
	;;
songs | loop | shuffle | list | lcat | like | dislike | next | pre | toggle | ss | status | list | close | Re | run)
	$1
	;;
P) $MYOWD/net.sh $1 ;;
cu | changeuid) change_uid ;;
[0-9]*) setnum $1 ;;
*) Help ;;
esac
